package day11.handler.simpleChannelHandler.request;

import day11.handler.simpleChannelHandler.response.GroupMessageResponseHandler;
import day11.packet.request.JoinGroupRequestPacket;
import day11.packet.response.GroupMessageResponsePacket;
import day11.packet.response.JoinGroupResponsePacket;
import day11.util.session.GroupSession;
import day11.util.session.Session;
import day11.util.session.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenshijie
 * @date 2024/1/2 14:09
 */

public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket joinGroupRequestPacket) throws Exception {
        // 1. 获取群对应的ChannelGroup，然后将当前用户的Channel添加进去
        int groupId = joinGroupRequestPacket.getGroupId();
        JoinGroupResponsePacket joinGroupResponsePacket = new JoinGroupResponsePacket();
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        if (channelGroup == null) {
            System.err.println("没有该群号");
            joinGroupResponsePacket.setFail();
            joinGroupResponsePacket.setGroupId(groupId);
        } else {
            channelGroup.add(ctx.channel());
            GroupSession groupSession = SessionUtil.getGroupSession(groupId);
            groupSession.setChannelGroup(channelGroup);
            List<Session> userSessions = groupSession.getUserSessions();
            userSessions.add(SessionUtil.getSession(ctx.channel()));

            // 2. 构造加群响应发给客户端

            joinGroupResponsePacket.setSuccess();
            joinGroupResponsePacket.setGroupId(groupId);
            List<String> userNameList = new ArrayList<>();
            for (Session userSession : userSessions) {
                userNameList.add(userSession.getUserName());
            }
            joinGroupResponsePacket.setMessage("群成员有" + userNameList);

            // 3. 入群通知
            GroupMessageResponsePacket groupMessageResponsePacket = new GroupMessageResponsePacket();
            groupMessageResponsePacket.setSuccess();
            groupMessageResponsePacket.setGroupId(groupId);
            groupMessageResponsePacket.setJoinGroupStatus(GroupMessageResponsePacket.JOIN_GROUP_STATUS);
            groupMessageResponsePacket.setFromUser(SessionUtil.getSession(ctx.channel()));
            channelGroup.writeAndFlush(groupMessageResponsePacket);
        }
        ctx.channel().writeAndFlush(joinGroupResponsePacket);
    }
}
